package com.alkalinesolutions.json.core;

import java.io.StringWriter;
import java.util.List;
import java.util.Map;

import com.alkalinesolutions.json.core.impl.CompactJSONTextEmitter;
import com.alkalinesolutions.json.core.impl.StructureWalker;

/**
 * Serializer instance which aims to produce the smallest possible JSON content.
 * To this end, it emits no whitespace and will not escape forward slashes or
 * unicode characters (unless required).
 * 
 * @author David Waite &lt;<a href='mailto:david@alkaline-solutions.com'>david@alkaline-solutions.com</a>&gt;
 * 
 */
public class CompactSerializer implements Serializer {

	protected CompactJSONTextEmitter handler;
	protected StringWriter writer;

	public CompactSerializer() {
		handler = new CompactJSONTextEmitter();
		writer = new StringWriter();
		handler.setWriter(writer);
	}

	protected void reset() {
		writer = new StringWriter();
		handler.setWriter(writer);
	}

	public String serialize(final Map<String, ? extends Object> object)
			throws JSONException {
		reset();
		handler.emitJSONText(StructureWalker.walk(this, object));
		return writer.toString();
	}

	public String serialize(final List<? extends Object> array)
			throws JSONException {
		reset();
		handler.emitJSONText(StructureWalker.walk(this, array));
		return writer.toString();
	}

	public String serialize(final Object[] array) throws JSONException {
		reset();
		handler.emitJSONText(StructureWalker.walk(this, array));
		return writer.toString();
	}
}
